﻿using B.S.BaseData.Infrastructure.Interfaces;
using B.S.ProcessEgine.ErrorCode;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace B.S.BaseData.Infrastructure.Implements
{
    public class BaseRepository<T>:IBaseRepository<T> where T : class
    {
        private readonly BaseDbContext _db;
        readonly ILogger<BaseRepository<T>> _logger;

        public BaseRepository(BaseDbContext db, ILogger<BaseRepository<T>> logger)
        {
            this._db = db;
            this._logger = logger;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T entity)
        {
            try
            {
                await _db.Set<T>().AddAsync(entity);
                return await _db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                //写异常日志
                _logger.LogError("添加出错" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="tlist"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> AddRangeAsync(IList<T> tlist)
        {
            try
            {
                await _db.Set<T>().AddRangeAsync(tlist);
                return await _db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                //写异常日志
                _logger.LogError("添加出错" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 显示
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            try
            {
                return _db.Set<T>().AsQueryable();
            }
            catch (Exception ex)
            {
                //写异常日志
                _logger.LogError("返回所有列表信息出错" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 单条件查询
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public async Task<T?> GetAsync(Expression<Func<T, bool>> expression)
        {
            try
            {
                return await _db.Set<T>().Where(expression).FirstOrDefaultAsync();
            }
            catch (Exception ex)
            {
                //写异常日志
                _logger.LogError("反填出错" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 反填ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<T?> GetByIdAsync(long id)
        {
            try
            {
                return await _db.Set<T>().FindAsync(id);
            }
            catch (Exception ex)
            {
                // 写异常日志
                _logger.LogError("反填出错！" + ex.Message);
                throw;
            }
        }

        public async Task<ApiPaging<T>> GetPageListAsync(int pageIndex, int pageSize, Expression<Func<T, bool>>? expression=null)
        {
            try
            {
                IQueryable<T> query = _db.Set<T>();

                //int count = await query.CountAsync();

                if (expression != null)
                {
                    query = query.Where(expression);
                }

                //分页
                int TotalCount=await query.CountAsync();
                int TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / pageSize);

                //数据
                var data = await query.Skip((pageIndex-1)*pageSize).Take(pageSize).ToListAsync();

                return new ApiPaging<T>(TotalCount,TotalPage,data);
            }
            catch (Exception ex)
            {
                _logger.LogError("分页出错！" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(T entity)
        {
            try
            {
                _db.Set<T>().Update(entity);
                return await _db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                //写异常日志
                _logger.LogError("修改出错" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="tlist"></param>
        /// <returns></returns>
        public async Task<int> UpdateRangeAsync(IList<T> tlist)
        {
            try
            {
                _db.Set<T>().UpdateRange(tlist);
                return await _db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                //写异常日志
                _logger.LogError("批量出错" + ex.Message);
                throw;
            }
        }
    }
}
